package ufc.great.ubilocation;

import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class FileListAdapter extends BaseAdapter {

	private List<LocationItem> filesList;
	private Context mContext;
	private String selectedItem;
	private LocationItem lastSelected;
	
	public FileListAdapter(Context mContext, List<LocationItem> elements) {
		filesList = elements;
		this.mContext = mContext;	
	}
	
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return filesList.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return filesList.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	static class ViewHolder {
		protected TextView fileName;
		protected RadioButton radioButton;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		LocationItem fileItem = filesList.get(position); 
		
		View rowView = convertView;
		
		if(rowView == null){
			final ViewHolder holder = new ViewHolder();
			rowView = (RelativeLayout) LayoutInflater.from(mContext).inflate(
					R.layout.filerow, parent, false);
			
			holder.fileName = (TextView) rowView.findViewById(R.id.listFileTextView);
			holder.radioButton = (RadioButton) rowView.findViewById(R.id.radioButton);
			
			holder.radioButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				
				public void onCheckedChanged(CompoundButton buttonview, boolean ischecked) {
					// TODO Auto-generated method stub
					LocationItem fileItem2 = (LocationItem) holder.radioButton.getTag();
					fileItem2.setSelected(buttonview.isChecked());
					if (ischecked){
						//selectedFile  = fileItem2.getName();
						UbiLocationActivity.setClickedFile(fileItem2);
						if(lastSelected == null){
							lastSelected = fileItem2;
						}else {
							if (!lastSelected.equals(fileItem2)){
								lastSelected.setSelected(false);
								lastSelected = fileItem2;
								notifyDataSetChanged();
							}
						}
					}
				}
			});
			
			rowView.setTag(holder);
			holder.radioButton.setTag(fileItem);
			
		} else {
			/*holder = (ViewHolder) rowView.getTag();*/
			((ViewHolder) rowView.getTag()).radioButton.setTag(fileItem);
		}
		
		//holder.fileIcon.setImageDrawable();
		ViewHolder holder = (ViewHolder) rowView.getTag();
		holder.fileName.setText(fileItem.getName());
	
		holder.radioButton.setChecked(fileItem.isSelected());
		//holder.icon
		 
		return rowView;
	}

}
